﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;
using XSTDZ.ERP.Infrastructure.Authentication;

namespace XSTDZ.ERP.WebApp.Controllers
{
    //盘点
    public class ProductCheckController : Controller
    {
        private readonly IProductCheckService productCheckBillServiceImpl = ServiceLocator.Instance.GetService<IProductCheckService>();	
        //
        // GET: /ProductIn/

        public ActionResult Index()
        {
            ViewBag.orgCode = SystemConfig.ChengDuCode;
            return View();
        }
        #region 查看详细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id)
        {
            var billModel = productCheckBillServiceImpl.GetProductCheckBill(id);
            return View(billModel);
        }
        #endregion
        #region 保存和提交统一入口
        [NoAuthorizated("AddAndConfirm")]
        [HttpPost]
        public ActionResult AddAndConfirm(ProductCheckBillDto roductInBillDto)
        {
            bool isConfirm = Convert.ToBoolean(Request["isConfirm"]);
            //订单已确认
            if (roductInBillDto.BillState > 0)
            {
                return new EmptyResult();
            }
            //保存(或更新)
            var aa = Add(roductInBillDto) as ContentResult;
            string actionResult = aa.Content.ToString();
            Guid tempId = Guid.Empty;
            if (Guid.TryParse(actionResult.ToString(), out tempId))
            {
                roductInBillDto.Id = tempId;
            }
            else
            {
                return Content(actionResult.ToString());
            }
            //提交
            if (isConfirm)
            {
              
                if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))//记录已存在
                {
                       ConfirmBill(roductInBillDto.Id);//提交
                }
            }
            return Content("9");
        }
        #endregion
        #region 添加盘点
        [NoAuthorizated("Add")]
        public ActionResult Add(string orgCode, Guid? id)
        {
            ProductCheckBillDto billModel = null;

            if (id == null || !id.HasValue)
            {
                var NO = new BusinessBillNoCreator().CreateCheckNextNO();

                var initSysData = DataInit.GetOrgAndDefaultWareHourse(orgCode);//初始化默认组织机构和仓库
                var wareHouse = initSysData.Values.FirstOrDefault();

                billModel = new ProductCheckBillDto
                {
                    CheckNo = NO,
                    StorehouseName = wareHouse.StorehouseName,
                    StorehouseID = wareHouse.Id
                };
             
            }
            else
            {
                Guid billId;
                Guid.TryParse(id.ToString(), out billId);
                billModel = this.productCheckBillServiceImpl.GetProductCheckBill(billId);

            }
            ViewBag.TempId = Guid.Empty;
            ViewBag.orgCode = orgCode;

            billModel.StartTime = DateTime.Today;// new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            billModel.EndTime = DateTime.Today;

            return View(billModel);
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(ProductCheckBillDto roductInBillDto)
        {

            var id = this.HttpContext.Request["StorehouseName_val"];
            #region 弹出框数据获取
            var model = new ProductCheckBillModel();
            //仓库ID
            var whId=model.GetRequestFormValues(this.HttpContext,"StorehouseName_val");
            if(!Guid.Empty.Equals(whId))
            {
              roductInBillDto.StorehouseID =whId;
            }
            //盘点人员
            var sendid = model.GetRequestFormValues(this.HttpContext, "CheckorName_val");
            if (!Guid.Empty.Equals(sendid))
            {
                roductInBillDto.CheckorID = sendid;
            }
            

            #endregion
            #region 主数据行处理
            
	        #endregion
            #region 明细行数据处理
		 

            var result = Request.Form["hidProductBillItems"];
            var detailItems = model.ConvertJosnToClass<ProductCheckBillDetailDto>(result);
            if (!string.IsNullOrEmpty(result) && detailItems == null)
            {
                return Content("-1");//明细行异常
            }
            var checkId = Guid.Empty;
            if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
            {
                checkId = roductInBillDto.Id;
            }
            detailItems.Each(item => {
                item.ProductCheckBillID = checkId;
                if (item.ID==null||item.ID.Equals(Guid.Empty))
                {
                    item.ID = Guid.Empty;
                }
            });
	        #endregion

            #region 数据验证
            if (detailItems == null || detailItems.Count <= 0)
            {
                ModelState.AddModelError("", "必须至少存在一个明细行！");
                return Content("-1");
            }
            #endregion
            if (ModelState.IsValid)
            {
                try
                {
                    if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
                    {
                        this.productCheckBillServiceImpl.UpdateProductCheckBill(roductInBillDto, detailItems);
                        return Content(roductInBillDto.Id.ToString());
                    }
                    else
                    {
                        roductInBillDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
                       var tempid= this.productCheckBillServiceImpl.AddProductCheckBill(roductInBillDto, detailItems);
                       return Content(tempid.ToString());
                    }
                }
                catch (Exception ex)
                {
                    return Content("-2");
                }
               
               // ViewBag.PostState = 9;
                return Content("9");
            }
            
            return Content("0");
        }
        #endregion
        #region 删除订单明细（假删除）
         [NoAuthorizated("Delete")]
        public ActionResult Delete(Guid billId,string ids)
        {
            
            if (ids!="all"&&ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                productCheckBillServiceImpl.ConvertProductCheckBillDeleteState(billId, guidIds);
                return Content("9");
            }
            else
            {
                productCheckBillServiceImpl.ConvertProductCheckBillDeleteState(billId);
                return Content("9");
            }
            
            return Content("0");
        }
        #endregion
        #region 更新至库存
         [NoAuthorizated("UpdateToStock")]
        public ActionResult UpdateToStock(Guid billId, string ids)
        {

            if (ids != "all" && ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                productCheckBillServiceImpl.UpdateToStock(billId, guidIds);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 提交
        [NoAuthorizated("ConfirmBill")]
        public ActionResult ConfirmBill(Guid billId)
        {
            if (!billId.Equals(Guid.Empty))
            {
                var NO = new BusinessBillNoCreator().CreateProfitAndLossNextNO();
                this.productCheckBillServiceImpl.Confirm(billId, NO);//生成损溢报告
                return Content("9");
            }
            return Content("0");
        }
        #endregion 
        #region 快速生成
          [NoAuthorizated("QuickCreate")]
        public ActionResult QuickCreate(Guid billId)
        {
            ViewBag.BillId = billId;
            return View();
        }
        [HttpPost]
        [NoAuthorizated("QuickCreate")]
        public ActionResult QuickCreate(Guid billId, string ids)
        {
             if (!billId.Equals(Guid.Empty)&& ids.Trim().Length > 0)
            {

                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();

                 IStockService stockServiceImpl = ServiceLocator.Instance.GetService<IStockService>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
              var list=  stockServiceImpl.GetStocksByIds(guidIds);
                 var checklst=new List<ProductCheckBillDetailDto>();
                 list.Each(t => {
                     checklst.Add(new ProductCheckBillDetailDto {
                         Amount=t.StockCount,
                          Deleted=0,
                         EntityAmount = t.StockCount,
                         ProductCheckBillID = billId,
                           StockID=t.ID,
                            Remarks="快速生成"
                     });
                 });
                 productCheckBillServiceImpl.UpdateProductCheckBill(billId, checklst);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 获取盘点列表数据
        //暂时获取所有数据
        [NoAuthorizated("GetJsonOfProductCheckBills")]
        public ActionResult GetJsonOfProductCheckBills()
        {
            #region  EF的查询，效率低下，故暂时放弃不用
            /*
            var productBills = productCheckBillServiceImpl.GetProductCheckBills(1, 100);
            if (productBills != null && productBills .Count() != 0)
            {
                var jsonResult = productBills.Select(u => { u.DeleteState = u.Deleted == 0 ? "正常" : "已删除";
                u.SettleState = u.IsSettle > 0 ? "已结算" : "未结算";
                         return u; 
                });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"10\"}";
                return Content(target);
            }
            
            return Content("");
            */
            #endregion

            return Content(new BLLQuery().GetProductCheckBills(this.HttpContext));
        }
        /// <summary>
        /// 根据盘点ID，获得盘点所有明细（不包括删除行）
        /// </summary>
        /// <param name="billId"></param>
        /// <returns></returns>
        [NoAuthorizated("GetJsonOfProductCheckBillDetails")]
        public ActionResult GetJsonOfProductCheckBillDetails(Guid billId)
        {
            #region EF的查询，效率低下，故暂时放弃不用
            //var billDetails = this.productCheckBillServiceImpl.GetProductCheckBillDetails(billId);//.Where(p => p.Deleted == 0).ToList();
            //if (billDetails != null && billDetails.Count() != 0)
            //{
            //    var jsonResult = billDetails.Select(b => { b.DeleteState = b.Deleted == 0 ? "正常" : "已删除"; return b; });
            //    var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
            //    target = "{\"Rows\":" + target + ",\"Total\":\"" + billDetails .Count()+ "\"}";
            //    return Content(target);
            //}

            // return Content("");
            #endregion
            if (!billId.Equals(Guid.Empty))
            {
                return Content(new BLLQuery().GetProductCheckDetails(billId));
            }
            else
            {
                return Content("");
            }
            
        }
        #endregion
        #region 深圳业务
         public ActionResult SZIndex()
        {
            ViewBag.orgCode = SystemConfig.ShengZhenCode;
            return View("Index");
        }
        #endregion
    }
}
